package com.shuhg.book.util
{
	import com.adobe.serialization.json.JSON;
	import com.shuhg.bean.BookBean;
	import com.shuhg.bean.BookParameter;
	import com.shuhg.book.view.TextBook;
	import com.shuhg.book.write.WriteBook;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.NativeWindowSystemChrome;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.geom.Matrix;
	import flash.net.FileFilter;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import shg.book.database.ConnectionDatabase;
	import shg.book.loadImage.LoadImage;
	import shg.book.size.BookData;

	public class ReadBook
	{
		public function ReadBook()
		{
		}
		 public var filePath:String;
		 private var bookLength:Number;
		
		
		 private var loadImage:LoadImage=new LoadImage();
		
		 //书籍的基本信息 
		 private var bookBean:BookBean;
		/**
		 * 打开书籍文件
		 * */
		 public function openBook():void{
			try{
				var fileFileter:FileFilter=new FileFilter("选择文件*.shg*.txt *.xml*.log","*.shg;*.txt;*.xml;.log");
				var file:File=new File();
				file.browseForOpen("选择书籍",[fileFileter]);
				file.addEventListener(Event.SELECT,selectFile);
			}catch(error:Error){
				trace("打开文件出现异常");
			}
		}
		/**
		 * 选择书籍文件
		 * */
		 public function selectFile(event:Event=null):void{
			try{
				if(filePath==null && event!=null)
					filePath=event.currentTarget.nativePath.toString();
				var request:URLRequest = new URLRequest(filePath);
				var loader:URLStream = new URLStream();
				if(filePath.substr(filePath.lastIndexOf(".")+1,filePath.length)=="shg"){
					loader.addEventListener(Event.COMPLETE, loaderFile);
				}else{
					var writeBook:WriteBook=new WriteBook();
					writeBook.title="电子书制作";
					writeBook.systemChrome=NativeWindowSystemChrome.NONE;
					writeBook.maximizable=false;
					writeBook.showStatusBar =false;
					writeBook.resizable=false;
					writeBook.alwaysInFront=true;
					writeBook.visible=false;
					writeBook.filePath = filePath;
					writeBook.open();
				}
				loader.load(request);
				trace(filePath);
			}catch(error:Error){
				trace("选择书籍文件出现了异常"+error.toString());
			}
		}
		/**
		 * 加载书籍文件
		 * */
		 public function loaderFile(event:Event):void{
			try{
				//将文件里面的内容一次型读取出来存储在字节数组里面
				var contentByte:ByteArray=new ByteArray();
				var fileStream:URLStream=event.currentTarget as URLStream;
				fileStream.readBytes(contentByte);
				fileStream.close();
				//解析内容
				resolveContent(contentByte);
			}catch(error:Error){
				trace("加载书籍文件出现异常");
			}
		}
		/**
		 * 解析内容
		 * */
		 public function resolveContent(bookByte:ByteArray):void{
			try{
				//前面15个字节是（版本控制）信息类（BookParameter） 15+信息类长度+内容长度+4个封面长度
				bookByte.position=0;
				var parameterLeng:Number = new Number(bookByte.readUTFBytes(BookData.EDITION_LENGTH));
				bookLength=BookData.EDITION_LENGTH + parameterLeng;//第一个15+信息类长度
				
				var parameter:String = bookByte.readUTFBytes(parameterLeng);
				var bookParameter:BookParameter = new BookParameter().initAPP(JSON.decode(parameter));
				
				//通过读取到的版本控制信息，将剩余的书籍信息和封面解释出来
				//书籍的内容Book
				var contentByte:ByteArray = new ByteArray();
				bookByte.readBytes(contentByte,0,bookParameter.contentLength);
				bookLength+=bookParameter.contentLength;
				//封面一
				var coverOne:ByteArray = new ByteArray();
				bookByte.readBytes(coverOne,0,bookParameter.coverOneLength);
				bookLength+=bookParameter.coverOneLength;
				//封面二
				var coverTwo:ByteArray = new ByteArray();
				bookByte.readBytes(coverTwo,0,bookParameter.coverTwoLength);
				bookLength+=bookParameter.coverTwoLength;
				//封面三
				var coverThree:ByteArray = new ByteArray();
				bookByte.readBytes(coverThree,0,bookParameter.coverThreeLength);
				bookLength+=bookParameter.coverThreeLength;
				//封面四
				var coverFour:ByteArray = new ByteArray();
				bookByte.readBytes(coverFour,0,bookParameter.coverFourLength);
				bookLength+=bookParameter.coverFourLength;
				//剩余都是批注
				var potil:String =bookByte.length-bookByte.position<1 ? null :  bookByte.readUTFBytes(bookByte.length-bookByte.position);
				//打开书籍面板
				openBookModel(coverOne,coverTwo,coverThree,coverFour,bookParameter,contentByte,potil);
				
			}catch(error:Error){
				trace("解析书籍内容发送异常可能是文件被修改"+error.message);
			}
		}
		/**
		 * 打开书籍面板
		 * */ 
		 private function openBookModel(coverOne:ByteArray,coverTwo:ByteArray,
											  coverThree:ByteArray,coverFour:ByteArray,
											  bookParameter:BookParameter,contentByte:ByteArray,potil:String):void{
			try{
				var openBook:TextBook=new TextBook();
				openBook.contentByte=contentByte;//内容
				openBook.bookPath = filePath;
				openBook.bookLength=bookLength;
				if(potil!=null)
					openBook.bookPotil =JSON.decode(potil);
				
				openBook.coverOne = BitmapByteUtil.ByteArrayToBitmap(coverOne);
				openBook.coverTwo = BitmapByteUtil.ByteArrayToBitmap(coverTwo);
				openBook.coverThree = BitmapByteUtil.ByteArrayToBitmap(coverThree);
				openBook.coverFour = BitmapByteUtil.ByteArrayToBitmap(coverFour);
				
				openBook.width = BookData.BOOK_WIDTH = bookParameter.bookWidth;
				openBook.height = BookData.BOOK_HEIGTH = bookParameter.bookHeigth;
				openBook.bookParameter=bookParameter;
				
				openBook.systemChrome=NativeWindowSystemChrome.NONE;
				openBook.maximizable=false;
				openBook.showStatusBar =false;
				openBook.resizable=false;
				openBook.open();
				//将当前的书籍保存的数据库里面并把书籍存储在书架上
				bookBean=new BookBean()
				this.bookBean.version = bookParameter.version;
				this.bookBean.bookId = bookParameter.bookId;
				this.bookBean.bookName = bookParameter.bookName;
				this.bookBean.pageCount = bookParameter.pageCount;
				this.bookBean.authorName = bookParameter.authorName; 
				this.bookBean.coverBitmap = openBook.coverOne;
				this.bookBean.filePath = this.filePath;
				this.bookBean.coverByte = coverOne;
				var time:Timer=new Timer(1000,1);
				time.addEventListener(TimerEvent.TIMER,saveToDataBase);
				time.start();
			}catch(error:Error){
				trace("打开书籍面板出现异常"+error.toString());
			}
		}
		 /**
		 * 将数据保存到数据库同时更新视图
		 * */
		 public function saveToDataBase(event:TimerEvent):void{
			 //工具书籍的ID到数据库里面查询数据，如果存在就不更新桌面视图（启动应用查询的时候已经更新）否则需要更新到桌面
			 var connection:ConnectionDatabase=new ConnectionDatabase();
			 connection.loadImage=this.loadImage;
			 connection.bookBean=this.bookBean;
			 connection.checkBook();
		 }
	}
}